package com.lanou.moving.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lanou.moving.R;
import com.lanou.moving.adapter.EveryoneMoreAdapter;
import com.lanou.moving.base.BaseActivity;
import com.lanou.moving.base.BaseApplication;
import com.lanou.moving.constant.URL;
import com.lanou.moving.entity.EveryoneMore;
import com.lanou.moving.entity.MusicInfo;
import com.lanou.moving.entity.dao.Collection;
import com.lanou.moving.entity.dao.CollectionDao;
import com.lanou.moving.entity.dao.RecentlyPlay;
import com.lanou.moving.entity.dao.RecentlyPlayDao;
import com.lanou.moving.eventBus.MyEventBus;
import com.lanou.moving.singleton.DaoSingleton;
import com.lanou.moving.view.CDSPopupWindow;
import com.lanou.moving.view.CommonProgressDialog;
import com.lanou.moving.volley.StringRequestUtf;
import com.lanou.moving.volley.VolleySingleton;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import it.sephiroth.android.library.picasso.Picasso;

/**
 * Created by 刘琪 on 15/10/28.
 */
public class EveryoneMoreActivity extends BaseActivity implements
        View.OnClickListener, EveryoneMoreAdapter.OnMenuClickListener, AdapterView.OnItemClickListener {
    private CollapsingToolbarLayout toolbarLayout;
    private Toolbar coordinator_toolbar;
    private VolleySingleton volleySingleton;
    private StringRequestUtf request;
    private List<EveryoneMore.DataEntity.SongsEntity> songsEntities;
    private ImageView everyone_more_bg;
    private ListView everyone_more_listview;
    private EveryoneMoreAdapter adapter;
    private String pic_url;
    private String url;

    //数据库表
    private CollectionDao collectionDao;
    private RecentlyPlayDao recentlyPlayDao;
    private View view;
    private TextView collect_tv;
    private ImageView rankingListBackground;
    private List<Collection> collections;
    private CDSPopupWindow pw;


    final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_everyone_more);
        BaseApplication.getInstance().addActivity(this);
        collectionDao = DaoSingleton.getInstance().getCollectionDao();
        recentlyPlayDao = DaoSingleton.getInstance().getRecentlyPlayDao();
        Intent intent = getIntent();
        pic_url = intent.getStringExtra("pic_url");

        initView();
        getData();
        initShare();
        QQShare();
    }

    private void initShare() {
        UMQQSsoHandler umqqSsoHandler = new UMQQSsoHandler(this, "100424468",
                "c7394704798a158208a74ab60104f0ba");
        umqqSsoHandler.addToSocialSDK();
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, "100424468",
                "c7394704798a158208a74ab60104f0ba");
        qZoneSsoHandler.addToSocialSDK();
    }

    private void QQShare() {
        QQShareContent qqShareContent = new QQShareContent();
        //设置分享文字
        qqShareContent.setShareContent("第一次分享东西， 好好看");
        //设置分享title
        qqShareContent.setTitle("哈哈哈");
        //设置点击分享内容的跳转连接
        qqShareContent.setTargetUrl(url);
        //????
        mController.setShareMedia(qqShareContent);
        QZoneShareContent qzone = new QZoneShareContent();
        //设置分享文字
        qzone.setShareContent("第一次给你分享东西，好好看");
        //设置分享内容的标题
        qzone.setTitle("哈哈哈");
        //设置点击消息的跳转URL
        qzone.setTargetUrl(url);
        mController.setShareMedia(qzone);
    }

    private void initView() {
        view = LayoutInflater.from(this).inflate(R.layout.layout_song, null);
        collect_tv = (TextView) view.findViewById(R.id.layout_song_collection);
        rankingListBackground = (ImageView) findViewById(R.id.everyone_background);

        volleySingleton = VolleySingleton.getInstance(this);
        everyone_more_bg = (ImageView) findViewById(R.id.everyone_more_bg);
        Picasso.with(this).load(pic_url).placeholder
                (R.mipmap.songlist_cover).error(R.mipmap.songlist_cover).into(everyone_more_bg);
        everyone_more_listview = (ListView) findViewById(R.id.everyone_more_listview);
        everyone_more_listview.setOnItemClickListener(this);
        toolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        toolbarLayout.setTitle("总有一首大家喜爱的歌能打动你");
        toolbarLayout.setExpandedTitleTextAppearance(R.style.Collapsed_Title_Text_appearance);
        toolbarLayout.setCollapsedTitleTextAppearance(R.style.Collapsed_Title_Text_appearance);
        coordinator_toolbar = (Toolbar) findViewById(R.id.coordinator_toolbar);
        coordinator_toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void getData() {
        request = new StringRequestUtf(URL.EVERYONE_MORE, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                EveryoneMore more = gson.fromJson(response, EveryoneMore.class);
                songsEntities = more.getData().getSongs();
                adapter = new EveryoneMoreAdapter(EveryoneMoreActivity.this, songsEntities);
                adapter.setOnMenuClickListener(EveryoneMoreActivity.this);
                everyone_more_listview.setAdapter(adapter);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(request);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onMenuClick(final EveryoneMore.DataEntity.SongsEntity songsEntity) {
        rankingListBackground.setVisibility(View.VISIBLE);
        collections = collectionDao.queryBuilder().where(
                CollectionDao.Properties.SongId.eq(songsEntity.getSongId())).list();
        if (collections != null && collections.size() > 0) {
            collect_tv.setText("取消收藏");
        } else {
            collect_tv.setText("收藏");
        }
        pw = new CDSPopupWindow(this, view, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.layout_song_collection:
                        if ("收藏".equals(collect_tv.getText())) {
                            Collection collection = new Collection();
                            collection.setSongId(songsEntity.getSongId());
                            collection.setSongName(songsEntity.getName());
                            collection.setPlayUrl(songsEntity.getUrlList().get(0).getUrl());
                            collection.setAlbumId(songsEntity.getAlbumId());
                            collection.setDuration((long) songsEntity.getUrlList().get(0).getDuration());
                            collection.setSingerName(songsEntity.getSingerName());
                            collectionDao.insert(collection);
                            collect_tv.setText("取消收藏");
                            Toast.makeText(EveryoneMoreActivity.this, "已收藏", Toast.LENGTH_LONG).show();
                            pw.dismiss();
                        } else if ("取消收藏".equals(collect_tv.getText())) {
                            collectionDao.queryBuilder().where(CollectionDao.Properties.SongId
                                    .eq(songsEntity.getSongId())).buildDelete()
                                    .executeDeleteWithoutDetachingEntities();
                            collect_tv.setText("收藏");
                            Toast.makeText(EveryoneMoreActivity.this, "已取消收藏", Toast.LENGTH_LONG).show();
                            pw.dismiss();
                        }
                        break;
                    case R.id.layout_song_download:
                        String download_url = songsEntity.getAuditionList().get(0).getUrl();
                        int size = songsEntity.getAuditionList().get(0).getSize();
                        CommonProgressDialog progressDialog = new CommonProgressDialog(EveryoneMoreActivity.this);
                        if (Environment.getExternalStorageState().equals(
                                Environment.MEDIA_MOUNTED)) {
                            // 下载路径
                            progressDialog.download(download_url, new File("/storage/emulated/0/Music/"));
                        }
                        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        progressDialog.show();
                        progressDialog.setMax(size);
                        progressDialog.setName(songsEntity.getName(), songsEntity.getSingerName());
                        break;
                    case R.id.layout_song_share:
                        mController.getConfig().removePlatform(SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN);
                        //是否只有已登录用户才能打开分享选择页
                        mController.openShare(EveryoneMoreActivity.this, false);
                        QQShare();
                        break;
                }

            }
        }, rankingListBackground);
        pw.showAtLocation(findViewById(R.id.everyone_background), Gravity.CENTER, 0, 0);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        EveryoneMore.DataEntity.SongsEntity songsEntity =
                (EveryoneMore.DataEntity.SongsEntity) parent.getItemAtPosition(position);
        if ((songsEntity.getUrlList() != null && songsEntity.getUrlList().size() > 0)) {
            RecentlyPlay recentlyPlay = new RecentlyPlay();
            recentlyPlay.setSongName(songsEntity.getName());
            recentlyPlay.setPlayUrl(songsEntity.getUrlList().get(0).getUrl());
            recentlyPlay.setDuration((long) songsEntity.getUrlList().get(0).getDuration());
            recentlyPlay.setSingerName(songsEntity.getSingerName());
            recentlyPlay.setSongId((long) songsEntity.getSongId());
            recentlyPlay.setResource("网络");
            recentlyPlayDao.insertOrReplace(recentlyPlay);

            EventBus.getDefault().post(new MyEventBus.PlayMusic(1));
            List<MusicInfo> musicInfoList = new ArrayList<>();

            for (EveryoneMore.DataEntity.SongsEntity entity : songsEntities) {
                if (entity.getUrlList() != null && entity.getUrlList().size() > 0) {
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setSongName(entity.getName());
                    musicInfo.setAlbum(entity.getAlbumName());
                    musicInfo.setAlbumId(entity.getAlbumId());
                    musicInfo.setUrl(entity.getUrlList().get(0).getUrl());
                    musicInfo.setDuration(entity.getUrlList().get(0).getDuration());
                    musicInfo.setSingerName(entity.getSingerName());
                    musicInfo.setResouce("网络");
                    musicInfoList.add(musicInfo);
                }
            }

            Intent intent = new Intent(EveryoneMoreActivity.this, PlayMusicActivity.class);
            EventBus.getDefault().post(new MyEventBus.Deliver(musicInfoList, songsEntity.getName()));
            intent.putExtra("songName", songsEntity.getName());
            intent.putExtra("duration", songsEntity.getUrlList().get(0).getDuration());
            intent.putExtra("resource", "网络");
            intent.putExtra("albumId", songsEntity.getAlbumId());
            intent.putExtra("singerName", songsEntity.getSingerName());
            startActivity(intent);
        } else {
            Toast.makeText(this, "暂时无法播放此歌曲", Toast.LENGTH_LONG).show();
        }

        url = songsEntities.get(position).getUrlList().get(0).getUrl();
    }
}
